package jtech.core;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;

public class ImageUtils {

	private static final GraphicsConfiguration gc;
	static {
		GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		GraphicsDevice graphicsDevice = environment.getDefaultScreenDevice();
		gc = graphicsDevice.getDefaultConfiguration();
	}
	
	public static BufferedImage createCompatibleImage(int w, int h, int transparency) {
		return gc.createCompatibleImage(w, h, transparency);
	}
	
	public static VolatileImage createVolatileImage(int w, int h, int transparency) {
		return gc.createCompatibleVolatileImage(w, h, transparency);
	}
	
	public static BufferedImage newImage(Image image, float scale, float alpha) {
		int w = (int) Math.ceil(image.getWidth(null) * scale);
		int h = (int) Math.ceil(image.getHeight(null) * scale);
		
		if (alpha < 0) {
			alpha = 0;
		} else if (alpha > 1f) {
			alpha = 1f;
		}

		int transparency = (alpha == 1f) ? Transparency.BITMASK : Transparency.TRANSLUCENT;
		
		BufferedImage buffered = createCompatibleImage(w, h, transparency);

		Graphics2D g2d = (Graphics2D) buffered.createGraphics();

		if (alpha < 1f) {
			AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
			g2d.setComposite(ac);
		}
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
//		g2d.drawImage(image.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING), 0, 0, null);
		g2d.drawImage(image, 0, 0, w, h, null);
		g2d.dispose();
		
		return buffered;
	}
	
}
